// tslint:disable
import { Component, OnInit, Input, OnDestroy } from "@angular/core";
import { ActionSheetController, AlertController } from "@ionic/angular";
import { ModalController } from "@ionic/angular";
import { Subscription } from "rxjs";
import { MessageService } from "src/app/shared/service/message.service";
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';

import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { NewBusinessInfoModalComponent } from '../new-business-info-modal/new-business-info-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { ShareFormModalComponent } from "../share-form-modal/share-form-modal.component";
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { RecommendModalComponent } from "../recommend-modal/recommend-modal.component";
import { PageModalService } from "src/app/shared/service/page-modal-service";
import { ModalFromCenterLeave, ModalFromCenterEnter } from "src/app/utils/transitions";

declare let $: any;
@Component({
  selector: 'app-order-list-style2',
  templateUrl: './order-list-style2.component.html',
  styleUrls: ['./order-list-style2.component.scss'],
})
export class OrderListStyle2Component implements OnInit {
  @Input() tagData: any;
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any = { content: {} };
  currentIndex = -1;
  sessionId = localStorage.getItem("sessionId");
  infoListId: any;
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "暂无数据";
  showLoadMore = false;
  pageSize: number;
  pageTotal: number;
  showDataLimit = -1;
  sectionCssStyle: any;
  contactTitle: any;
  contactTitleCssStyle: any;
  listenerName: any;
  noNeedLoading: any;
  hiddenArrow = false;
  noNeednoDataSpan = true;
  public refreshIds = new Set(); // 2024.10.16 refreshIds
  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private shareService: ShareService,
    private pageModalService: PageModalService,
    public modalController: ModalController) {
  }

  updateSingleData(param) {
    let that = this;
    if (param['keyValue'] !== undefined) {
      let viewId = '';
      let pluginId: any;
      const page: any =  JSON.parse(JSON.stringify(this.appGlobalService.getCurrentTarget())) ;
      if (page.params) {
      } else {
        page.params = {}
      }
      if (this.tagData.data.data[that.dataIndex].viewId !== undefined
        && this.tagData.data.data[that.dataIndex].viewId !== '0') {
        if (this.appGlobalService.currentPartParams) {
          this.appGlobalService.consoleLog('refresh use current part params ...', '  	   ');
          page.params = JSON.parse(JSON.stringify( this.appGlobalService.currentPartParams)) ;
        }
      }
      page['sessionId'] = localStorage.getItem('sessionId')
      if (param['keyValue'] !== undefined) {
        page[param['key']] = param['keyValue']
      } else {
        const arr = param.result.split(',');
        page[param['key']] = arr[0];
      }
      if (param['viewId']) {
        viewId = param['viewId']
      }
      page.params['ajax'] = 'true';
      if (param['pluginId']) {
        page.params['pluginId'] = param['pluginId']
      }
      
      page['viewId'] = viewId;
      if (param['viewId']) {
        viewId = param['viewId']
        page['viewId'] = viewId;
        const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
        if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
          page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
        }
        const url = this.httpService.bathUrl + 'application/part';
        this.pageModalService.jsongetPostData(url, page, (res) => {
          // this.httpService.post('application/part', page, res => {
          try {
            const tagData = JSON.parse(res.script).tags;
            if (tagData) {
              tagData.forEach(element => {
                if (element && element.style.includes('singleManageListTag') && element.data.data.length === 1) {
                  that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
                } else if (element && element.style.includes('singleManageListTag') && element.data.data.length > 1) {
                  let tagDataArray = that.tagData.data.data;
                  let elementDataArray = element.data.data;
                  // 遍历 elementDataArray  
                  elementDataArray.forEach(element => {
                    // 在 tagDataArray 中查找与当前元素 id 相同的元素  
                    let foundIndex = tagDataArray.findIndex(tagData => tagData.id === element.id);
                    if (foundIndex !== -1) {
                      // 如果找到了，就用 element 替换 tagDataArray 中对应的元素  
                      tagDataArray[foundIndex] = element;
                    }
                  });
                }
              });
            }
          } catch (error) {
            console.log(error);
          }

        });
      } else {
        // 2024.08.29 无viewId则表示为submit提交
        this.appGlobalService.consoleLog('无viewId', '  	   ');
        if (this.tagData && this.tagData.data && this.tagData.data.submit) {
          this.tagData.data.submit[param.key] = param.keyValue;
        }
        this.updateItem(param);
      }






    } else {
      const tempParams = {
        content: this.tagData.data.submit.content,
        id: this.tagData.data.submit.id,
        sessionId: localStorage.getItem("sessionId"),
      }
      this.httpService.post('application/submit', tempParams, res => {
        if (res.success) {
          if (param.updateType !== undefined && param.updateType === 'refresh') {
            this.tagData.data.data = res.data.data;
          } else {
            let foundValue = res.data.data.find(item => item.id === param.value);
            let date = new Date().toLocaleString() + '.' + new Date().getMilliseconds();
            foundValue['isUpdate'] = date;
            for (let index = 0; index < this.tagData.data.data.length; index++) {
              const element = this.tagData.data.data[index];
              if (element.id === param.value) {
                this.tagData.data.data[index] = foundValue;
              }
            }
          }
        }
      });
    }

  }

  ngOnInit() {
    // 新增处理刷新
    if (this.tagData.name.includes('_singleData')) {
      const singleDataTagName = this.tagData.name;
      if (this.eventService.eventEmit.listenerCount(singleDataTagName) > 0) {
        this.eventService.eventEmit.removeListener(singleDataTagName);
      }
      this.eventService.eventEmit.on(singleDataTagName, (res) => {
        this.updateSingleData(res);
      });
    }


    console.log('初始化', '' + new Date().toLocaleDateString());
    this.listenerName = this.tagData.name + 'AskForList';
    //1.9.0 维保 最新改动版本 检查列表是否有多次请求的情况 有的话就取最新的
    if (this.eventService.eventEmit.listenerCount(this.listenerName) > 0) {
      this.eventService.removeCustomListListenersByName(this.listenerName);
    }
    this.eventService.eventEmit.on(this.listenerName, (obj) => {
      this.refreshListData(obj);
    });

    this.params = this.tagData.data.submit;
    if (this.tagData && this.tagData.hint) {
      this.emptyDataHint = this.tagData.hint;
    }

    const arry = this.tagData.data.data;
    if (arry) {
      if (arry[0] && arry[0].secondRowSettings && arry[0].secondRowSettings.limit) {
        this.showDataLimit = parseInt(arry[0].secondRowSettings.limit);
      }
      if (arry[0] && arry[0].sectionCssStyle) {
        this.sectionCssStyle = arry[0].sectionCssStyle;
      }
      if (arry[0] && arry[0].contactTitle) {
        this.contactTitle = arry[0].contactTitle;
      }
      if (arry[0] && arry[0].contactTitleCssStyle) {
        this.contactTitleCssStyle = arry[0].contactTitleCssStyle;
      }
      if (arry[0] && arry[0].noNeedLoading) {
        this.noNeedLoading = arry[0].noNeedLoading;
      }
    }


    if (!this.subscription && this.tagData.data.submit !== undefined) {
      if (
        this.tagData.data.submit.content &&
        this.tagData.data.submit.content.showName
      ) {
        sessionStorage.setItem(
          "showName",
          this.tagData.data.submit.content.showName
        );
      } else {
        sessionStorage.removeItem("showName");
      }
      this.message.clearMessage();
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {

        if (param === undefined) {
          return;
        } else if (param.type === 'ionRefresh') {
          this.refreshData(param);
          return;
        }
        this.pageNo = 1;
        this.params.sessionId = localStorage.getItem("sessionId");
        // 参数
        this.params.content = param;
        // 页面数据参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post(
          "application/submit",
          this.params,
          res => {
            console.log("submit");
            // 请求数据成功
            if (res.success) {
              const result = res.data.data;
              // 筛选数据
              this.tagData.data.data = result;
              this.cssStyle();
              // 自动回到顶部
              setTimeout(() => {
                const el = document.getElementById('information0');
                if (el) {
                  el.scrollIntoView(true);
                }

              }, 200);
            } else {
              // 请求数据失败
              this.appGlobalService.showToast(res.message, 2000, "middle");
            }
          },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, "middle");
          }
        );
      });


    }


    if (this.tagData.data && this.tagData.data.data) {
      for (let index = 0; index < this.tagData.data.data.length; index++) {
        const element = this.tagData.data.data[index];
        if (element.payList !== undefined) {
          if (element.newCommentBox && element.newCommentBox.amount && element.newCommentBox.unit) {
            // element.payList.unsift(element.newCommentBox);
            const jArry = [];
            jArry.push({ newComment: element.newCommentBox });
            for (let j = 0; j < element.payList.length; j++) {
              const jel = element.payList[j];
              jArry.push(jel);
            }
            element.payList = jArry;
            console.log('payList=', element.payList);
          }
        }
      }
    }

    this.infoListId += new Date().getTime();


    if (this.tagData.data.headDiv !== undefined
      && this.tagData.data.headDiv.sectionBox !== undefined
      && this.tagData.data.headDiv.sectionBox.hiddenArrow !== undefined) {
      if (this.tagData.data.headDiv.sectionBox.hiddenArrow === 'true') {
        this.hiddenArrow = true;
        $("#orderInfoList" + this.infoListId).hide();
      } else if (this.tagData.data.headDiv.sectionBox.hiddenArrow === 'false') {
        this.hiddenArrow = false;
      }
    }

  }



  ngAfterViewInit(): void {
    let that = this;
    // 2023.12.08 是否存在刷新控件
    if (that.tagData
      && that.tagData.data
      && that.tagData.data.data
      && that.tagData.data.data.length > 0) {
      setTimeout(() => {
        // 2023.12.08 配置了某个属性才检查是否有下拉刷新事件
        if (that.tagData.data.data[0].isShowRefresher === 'true') {

          const debouncedHandler = that.appGlobalService.debounce((data: any) => {
            if (that.tagData.refreshId !== undefined) {
              that.eventService.eventEmit.emit(that.tagData.refreshId, '1');
            }
          }, 300);
          that.eventService.eventEmit.on('checkListIsShowRefresher', debouncedHandler);

          if (that.tagData.refreshId !== undefined) {
            that.tagData.refreshId += 'a';
            that.refreshIds.add(that.tagData.refreshId);
            // this.eventService.eventEmit.on(that.tagData.refreshId, data => {
            //   this.appGlobalService.consoleLog('checkListIsShowRefresher EventEmit.on', that.tagData.refreshId);
            //   let tempRefresher = true;
            //   if (tempRefresher) {
            //     tempRefresher = false;
            //     let tempParamsContent = {};
            //     if (!that.params) {
            //       that.params = { content: {} };
            //       if (that.tagData.data.submit.content) {
            //         that.params.content = that.tagData.data.submit.content;
            //       }
            //     } else {
            //       if (that.params && that.params.content) {
            //         tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
            //       }
            //     }
            //     that.refreshListData(tempParamsContent);
            //     setTimeout(() => {
            //       tempRefresher = true; //防止2秒内重复请求
            //     }, 2000);
            //   }
            // });
            const debouncedHandler2 = that.appGlobalService.debounce((data: any) => {
              let tempRefresher = true;
              if (tempRefresher) {
                tempRefresher = false;
                let tempParamsContent = {};
                if (!that.params) {
                  that.params = { content: {} };
                  if (that.tagData.data.submit.content) {
                    that.params.content = that.tagData.data.submit.content;
                  }
                } else {
                  if (that.params && that.params.content) {
                    tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
                  }
                }
                that.refreshListData(tempParamsContent);
                setTimeout(() => {
                  tempRefresher = true; //防止2秒内重复请求
                }, 2000);
              }
            }, 300);
            that.eventService.eventEmit.on(that.tagData.refreshId, debouncedHandler2);
          }
          
        }
      }, 100);

    }
  }


  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.submit && this.tagData.data.submit.content && this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    this.params.content = param;
    this.params.id = this.tagData.data.submit.id;
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }




  /**
   *
   * @param item 渲染页面按钮样式
   * @param dataIndex
   */
  cssStyle() {
    if (this.tagData.data && this.tagData.data.data) {
      this.tagData.data.data.forEach(data => {
        if (
          data.fourthRowLeft && data.fourthRowLeft.firstText &&
          data.fourthRowLeft.firstText.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.firstText.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstText.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTag &&
          data.fourthRowLeft.secondTag.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTag.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTag.childCss = childCss;
        }
        if (data.fourthRowLeft && data.fourthRowLeft.firstTag && data.fourthRowLeft.firstTag.cssStyle) {
          const cssStyles = data.fourthRowLeft.firstTag.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {

            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstTag.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTest &&
          data.fourthRowLeft.secondTest.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTest.cssStyle.split(";");
          const childCss = {};

          for (let i = 0; i < cssStyles.length; i++) {

            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTest.childCss = childCss;
        }
      });
    }

  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  // 分享弹框
  async presentShare58Modal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      backdropDismiss: true,
      component: ShareFormModalComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  async presentAlertWithMsgBtn(msg, btnText, button) {
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: btnText,
          handler: () => {
            // this.httpService.changeCallNumber(mobile);
            const params = {
              content: button.submit.content,
              id: button.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                this.appGlobalService.reloadCurrentPage();
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  /**
   *
   * @param item 点击图标
   */
  iconClick(item, singleData?) {
    const that = this;
    if (item.modelType === "iconSubmit") {
      const params = {
        content: item.button.submit.content,
        id: item.button.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (item.link && item.link.target) {
            if (res.data && res.data.eventResult) {
              item.link.params[item.link.params.eventResult] = res.data.eventResult;
            }
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
            return;
          }
        } else {
          return;
        }
      });
    } else if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          this.presentShareModal(tmpShareData);
        });
      } else {
        // 修改
        // const params = {
        //   pageId: item.link.target,
        //   params: item.link.params,
        //   sessionId: localStorage.getItem("sessionId")
        // };
        // this.appGlobalService.goToForward(params);
        this.pageModalService.openPage(item.link);
      }
    } else if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    } else if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.userName !== undefined ? item.userName : item.label);
      }
    } else if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    } else if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    } else if (item.modelType === "remarkList") {
      if (item.listRemark) {
        this.remarkList(item);
      } else if (singleData && singleData.childIconList) {
        this.remarkList(singleData);
      }
    } else if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    } else if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      } else if (singleData && singleData.childIconList) {
        this.remarkList(singleData);
      }
    } else {
      if (item.link) {
        if (item.link.type === 'page') {
          const params = {
            pageId: item.link.target,
            params: item.link.params,
            sessionId: localStorage.getItem("sessionId")
          };
          this.appGlobalService.goToForward(params);
        } else if (item.link.type === 'model' || item.link.type === 'modal' || item.link.type === 'pageModal') {
          if (!item.link.params.modalCss) {
            item.link.modalCss = 'auto-modal';
          }
          this.pageModalService.openPage(item.link, '', result => {
            // that.updateItem();
            if (item.label && item.label === '取消订单' || item.link.params.needDel) {
              that.tagData.data.data.splice(that.dataIndex, 1);
            }
            else if(item.link.params.checkResult!==undefined && !result) return;
            else {
              that.updateItem(item);
            }
          });

        } else if (item.link.type === 'url' || item.link.type === 'chat') {
          this.pageModalService.openPage(item.link);
        } else {
          this.pageModalService.openPage(item.link);
        }
      }
      if (item.button) {

        if (item.action && item.action === 'question') {
          this.presentAlertWithMsgBtn(item.msg, item.text ? item.text : '确定', item.button);
        } else {

          if (item.button.submit && item.button.submit.content.formType) {
            const params = {
              content: item.button.submit.content,
              id: item.button.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.message && res.message.length > 0) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
              }
            });

          } else {
            this.presentAlertWithMsgBtn1(item.button.submit);
          }

        }


      }
    }
  }

  async presentAlertWithMsgBtn1(submit) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {

            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                that.updateItem();

              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  leftButtonList(leftButton) {
    const that = this;
    if (leftButton.leftButtonChildIconList) {
      leftButton.listRemark = leftButton.leftButtonChildIconList;
      that.selectItem(leftButton, 0);
    }
  }



  remarkList(more) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );



  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      this.pageModalService.openPage(itemObj.link);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    } else if (itemObj.modelType === 'question') {
      // 1.7.0 add
      this.presentQuestion(itemObj, itemObj.msg, index);
    } else {
      if (itemObj.link) {
        if (itemObj.link.type === 'page') {
          const params = {
            pageId: itemObj.link.target,
            params: itemObj.link.params,
            sessionId: localStorage.getItem("sessionId")
          };
          this.appGlobalService.goToForward(params);
        } else if (itemObj.link.type === 'model' || itemObj.link.type === 'modal' || itemObj.link.type === 'pageModal') {
          if (!itemObj.link.params.modalCss) {
            itemObj.link.modalCss = 'auto-modal';
          }
          this.pageModalService.openPage(itemObj.link, '', result => {

            if (itemObj.label && itemObj.label === '取消订单' || itemObj.link.params.needDel) {
              this.tagData.data.data.splice(this.dataIndex, 1);
            } else {
              this.updateItem(itemObj);
            }

          });

        } else if (itemObj.link.type === 'url' || itemObj.link.type === 'chat') {
          this.pageModalService.openPage(itemObj.link);
        }
      }
    }
  }

  async presentQuestion(itemObj, msg, dataIndex) {

    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let submitParam;
            if (itemObj.submit) {
              submitParam = itemObj.submit;
            } else if (itemObj.button) {
              submitParam = itemObj.button.submit;
            }
            const params = {
              content: submitParam.content,
              id: submitParam.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              this.appGlobalService.showToast(res.message, 1500, "middle");
              if (res.success) {
                if (itemObj.refresh !== undefined) {
                  this.appGlobalService.reloadCurrentPage();
                } else {
                  if (dataIndex >= 0 && dataIndex < this.tagData.data.data.length) {
                    this.tagData.data.data.splice(dataIndex - 1, 1);
                  }
                  if (this.tagData.data.data.length === 0) {
                    //1.7.0 新增
                    this.tagData.data.moreButton = {};
                  }
                }
              }
            });
          }
        }
      ]
    });

    await alert.present();
  }
  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          ActionSheetService.close();
          that.iconClick(icons[buttonIndex]);
        }
      }
    );
  }
  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }
  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }
  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }
  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;

    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }
  go(item, e, type?) {
    e.stopPropagation();
    if (type !== undefined) {
      if (item.contactInfo !== undefined) {
        if (type === 'chat') {
          this.pageModalService.openPage(item.contactInfo.chat.link);
        } else if (type === 'phone') {
          this.pageModalService.openPage(item.contactInfo.phone.link);
        } else if (type === 'design') {
          this.pageModalService.openPage(item.contactInfo.degsin.link);
        } else if (type === 'list') {
          if (item.contactInfo.listBeforeSubmit !== undefined) {
            const params = {
              content: item.contactInfo.listBeforeSubmit.content,
              id: item.contactInfo.listBeforeSubmit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1000, "bottom");
              } else {
                this.appGlobalService.showToast(res.message, 1000, "bottom");
              }
            });
          }
          this.pageModalService.openPage(item.contactInfo.list.link);
        } else if (type === 'pictures') {
          this.pageModalService.openPage(item.contactInfo.pictures.link);
        }
      }
      return;
    }
    if (item.title !== undefined) {
      this.pageModalService.openPage(item.link, item.title);
    } else {
      this.pageModalService.openPage(item.link);
    }
  }

  pullToRefresh() {

  }
  refreshData(event?) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;
          this.cssStyle();

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    this.noNeednoDataSpan = false;
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
              this.cssStyle();
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }

        this.noNeednoDataSpan = true
      });
    }, 500);
  }

  openModalLink(item, label) {
    try {
      if (label === '业务中' || label === '签约中') {
        if (item && item.type === 'modal') {
          this.openNewBusinessInfoModal("recommend-modal", item);
        }
      } else {
        return;
      }

    } catch (error) {
    }
  }

  async openNewBusinessInfoModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.target,
        params: item.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData.data && tagData.data.length > 0) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: NewBusinessInfoModalComponent,
            componentProps: { tagData }
          });
          await modal.present();
          // 监听销毁的事件
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
          });
          await modal.present();
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  gotoSharePage(obj) {
    if (obj.tips) {
      this.appGlobalService.showToast(obj.tips, 2000, "middle");
      return;
    }
    if (obj && obj.label) {
      switch (obj.label) {
        case 'qq':
          this.shareService.shareQQ(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'qzone':
          this.shareService.shareQQZone(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'wechat':
          this.shareService.shareWeiXin(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'moment':
          this.shareService.shareMoments(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case '58':
          this.shareService.share58(obj);
          break;
        case 'tikTok': // 抖音
          if (obj.isInValidImgPosterSharing) {
            // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
            // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
            this.shareService.shareDouyinForInValidImg(obj.link.fieldLinkType);
          } else {
            this.shareService.shareDouyin(obj.title, obj.content, obj.imageUrls, obj.webpageUrl, obj.shareType);
          }
          break;
        case 'kwai': // 快手 https://play.google.com/store/apps/details?id=com.kwai.video&hl=zh&gl=US
          this.shareService.shareKuaishou(obj.title, obj.content, obj.imageUrl, obj.webpageUrl, obj.shareType);
          break;
        case 'copy':
          this.shareService.copyUrl(obj.webpageUrl);
          break;
        case 'savePic':
          // this.shareService.savePic();
          break;
        case 'posterSharing':
          this.shareService.posterSharing(obj.link.fieldLinkType);
          break;
        default:
          console.log('...gotoSharePage');
          break;
      }

    }
  }

  openShareModal(obj) {
    if (obj) {
      let subject = obj;
      if (obj.shareBtn && obj.shareBtn.fieldLinkType) {
        subject = obj.shareBtn.fieldLinkType;
      }
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: subject.link.target,
        params: subject.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        this.presentShareModal(tmpShareData);
      });
    }
  }

  async previewImage(imageUrl, tmpIndex, isPreview) {
    // event.stopPropagation();
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }

  }


  call(phone, name) {
    event.stopPropagation();
    this.presentAlertConfirm(Number(phone), name);
  }
  morebtnClick(moreLink, index) {
    if (!moreLink) {
      return;
    }
    this.dataIndex = index;
    this.showActionSheet(moreLink);
  }
  normalBtnClick(buttonItem, index, singleData?) {
    if (!buttonItem) {
      return;
    }
    this.dataIndex = index;
    this.iconClick(buttonItem, singleData);
  }

  gotoPage(obj) {
    try {
      if (obj) {
        const targetObj = { pageId: obj.target, params: obj.params, sessionId: localStorage.getItem('sessionId') };
        this.appGlobalService.goToForward(targetObj);
      }
    } catch (error) {
    }
  }

  updateItem(item?) {
    const that = this;
    if (!item && !this.tagData.data.data[that.dataIndex].id) {
      return;
    }
    const page: any = JSON.parse(JSON.stringify(this.appGlobalService.getCurrentTarget()));
    if (page.params) {
    } else {
      page.params = {}
    }
    if (this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      if (this.appGlobalService.currentPartParams) {
        this.appGlobalService.consoleLog('refresh use current part params ...', '  	   ');
        page.params = JSON.parse(JSON.stringify(this.appGlobalService.currentPartParams));
      }
    }
    if (item && item.key && item.keyValue) {
      const data = this.tagData.data.data;
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        if (element[item.key] === item.keyValue) {
          if (element.updateItemType === undefined && item.updateItemType) {
            element['updateItemType'] = item.updateItemType;
          } else if (element.updateItemType && item.updateItemType) {
            element['updateItemType'] = item.updateItemType;
          }
          page.params = {}
          if (element.pageId !== undefined) {
            page.pageId = element.pageId;
            page['sessionId'] = localStorage.getItem('sessionId');
          }
          that.dataIndex = index;
          break;
        }

      }
    }
    if (item !== undefined && item.updateItemType === 'delete') {
      that.tagData.data.data.splice(this.dataIndex, 1);
      return;
    }
    if (this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      if (this.tagData.data.data[that.dataIndex].customParamName) {
        page.params[this.tagData.data.data[that.dataIndex].customParamName]
          = this.tagData.data.data[that.dataIndex][this.tagData.data.data[that.dataIndex].customParamName];
      }
      page.params['ajax'] = 'true';
      page.params['opportunity_opportunity_id'] = this.tagData.data.data[that.dataIndex].id;
      page['viewId'] = this.tagData.data.data[that.dataIndex].viewId;
      page['sessionId'] = localStorage.getItem('sessionId');
      const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
      if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
        page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
      }
      const url = this.httpService.bathUrl + 'application/part';
      this.pageModalService.jsongetPostData(url, page, (resData) => {
        const tagData = JSON.parse(resData.script).tags;
        if (tagData) {
          tagData.forEach(element => {
            if ((element.style.includes('appInfoListTag') || element.style.includes('orderListTag')) && element.data && element.data.data[that.dataIndex]) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[that.dataIndex]);
            } else if (element && element.style.includes('orderListTag') && element.data.data.length === 1) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
            } else if (element && element.style.includes('orderListTag') && element.data.data.length > 1) {
              let tagDataArray = that.tagData.data.data;
              let elementDataArray = element.data.data;
              // 遍历 elementDataArray  
              elementDataArray.forEach(element => {
                // 在 tagDataArray 中查找与当前元素 id 相同的元素  
                let foundIndex = tagDataArray.findIndex(tagData => tagData.id === element.id);
                if (foundIndex !== -1) {
                  // 如果找到了，就用 element 替换 tagDataArray 中对应的元素  
                  tagDataArray[foundIndex] = element;
                }
              });
            }
          });
        }
      });

    } else {
      if (this.tagData.data.data[that.dataIndex].id) {
        page.params.id = that.tagData.data.data[that.dataIndex].id;

        if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
          && that.tagData.data.data[that.dataIndex].updateItemType === 'delete') {
          that.tagData.data.data.splice(this.dataIndex, 1);
          return;
        }
        const needAddIsShell = (that.tagData.isShell && that.tagData.isShell !== "false");
        if (needAddIsShell) { // 2024.09.23 根据接口返回的参数来判断
          page.params['isShell'] = true; // 2024.09.10 防止接口请求两次
        }
        const url = this.httpService.bathUrl + 'application/page';
        this.pageModalService.jsongetPostData(url, page, (res) => {
          // this.httpService.post('application/page', page, async res => {
          const tagData = JSON.parse(res.script).views[0].tags;
          tagData.forEach(element => {
            if (element.style === 'orderListTag' && element.data && element.data.data[0]) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
            } else if (element.style === 'tag.AppTabTagLogic' && element.currentData && element.currentData.tags) {
              element.currentData.tags.forEach(e => {
                if (e.style === 'orderListTag' && e.data && e.data.data[0]) {
                  that.tagData.data.data.splice(that.dataIndex, 1, e.data.data[0]);
                }
              }
              )
            }
          });
        });
      }
    }
  }
  ngOnDestroy(): void {
    if (this.tagData && this.refreshIds) {
      this.refreshIds.forEach(element => {
        this.eventService.removeCustomListListenersByName(element);
      });
    }
    // this.eventService.removeCustomListListeners();
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  getInterger(value) {
    return parseInt(value);
  }

  openImg(event, imgs, i) {
    event.stopPropagation();
    this.pageModalService.openImage_url(i, imgs);
  }
  gotoChat(item) {
    if (item.link.type && item.link.type === 'chat') {
      this.httpService.gotoChat(item);
    }
  }

  copyClick(event, label) {
    this.appGlobalService.copyStr(event, label, label);
  }


  upOrDownDiv() {
    this.hiddenArrow = !this.hiddenArrow;
    if ($("#orderInfoList" + this.infoListId).is(":hidden")) {
      $("#orderInfoList" + this.infoListId).slideDown();
    } else {
      $("#orderInfoList" + this.infoListId).slideUp();
    }
  }
}
